package org.dxy.service.impl;

import org.dxy.entity.Order;
import org.dxy.entity.User;
import org.dxy.entity.Trip;
import org.dxy.Repository.orderMapper;
import org.dxy.Repository.UserRepository;
import org.dxy.Repository.TripRepository;
import org.dxy.mapper.OrderMapper;
import org.dxy.mapper.TripMapper;
import org.dxy.mapper.UserMapper;
import org.dxy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

// 订单服务实现类
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TripMapper tripMapper;

    @Override
    public Order createOrder(Long userId, Long tripId, String seatType, String seatNumber, BigDecimal totalPrice) {
        User user = userMapper.findById(userId).orElse(null);
        Trip trip = tripMapper.findById(tripId).orElse(null);
        if (user!= null && trip!= null) {
            Order order = new Order();
            order.setUser(user);
            order.setTrip(trip);
            order.setSeatType(seatType);
            order.setSeatNumber(seatNumber);
            order.setTotalPrice(totalPrice);
            order.setStatus("未支付");
            order.setOrderTime(LocalDateTime.now());
            return orderMapper.save(order);
        } else {
            return null;
        }
    }

    @Override
    public Order payOrder(Long orderId) {
        Order order = orderMapper.findById(orderId).orElse(null);
        if (order!= null) {
            order.setStatus("已支付");
            return orderMapper.save(order);
        } else {
            return null;
        }
    }

    @Override
    public List<Order> getUserOrders(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.findAll();
    }

    @Override
    public void cancelOrder(Long orderId) {
        Order order = orderMapper.findById(orderId).orElse(null);
        if (order!= null) {
            order.setStatus("已取消");
            orderMapper.save(order);
        }
    }
}